import {Component, OnInit} from '@angular/core';

@Component({
    selector: 'app-time',
    templateUrl: './time.component.html',
    styleUrls: ['./time.component.less']
})
export class TimeComponent implements OnInit {
    public date: any;
    constructor() {
    }

    ngOnInit() {
        this.date = this.getDate();
        this.start();
    }
    addZero(val) {
        if (val < 10) {
            val = '0' + String(val);
        }
        return val;
    }
    // 获取当前时间
    getDate() {
        const date = new Date();
        const year = date.getFullYear();
        const month = date.getMonth() + 1;
        const day = date.getDate();
        const hour = date.getHours();
        const minute = date.getMinutes();
        const second = date.getSeconds();
        return {
            year: year,
            month: this.addZero(month),
            day: this.addZero(day),
            hour: this.addZero(hour),
            minute: this.addZero(minute),
            second: this.addZero(second)
        };
    }
    start() {
        setTimeout(() => {
            if (parseInt(this.date.second, 10) < 60) {
                this.date.second = this.addZero(parseInt(this.date.second, 10) + 1);
            } else {
                this.date.second = '01';
                if (parseInt(this.date.minute, 10) < 60) {
                    this.date.minute = this.addZero(parseInt(this.date.minute, 10) + 1);
                } else {
                    this.date.minute = '01';
                    if (parseInt(this.date.hour, 10) < 24) {
                        this.date.hour = this.addZero(parseInt(this.date.hour, 10) + 1);
                    } else {
                        this.date.hour = '01';
                    }
                }
            }
            this.start();
        }, 1000);
    }
}
